import { ref, computed, watch } from 'vue';

/**
 * 表格选择相关hook
 * 处理表格行选择和批量操作
 * @param {Object} options - 配置选项
 * @returns {Object} - 返回选择相关状态和方法
 */
export function useTableSelection(options) {
  const {
    rowKey = 'id', // 行数据主键
    dataSource = [], // 表格数据源
    onSelectionChange = null, // 选择变化回调
    isSelectable = null, // 行是否可选判断函数
    preserveSelectedOnPageChange = false, // 分页变化时保留选择
    selectedRowKeys: propsSelectedKeys = null, // 外部控制的选中行
    defaultSelectedRowKeys = [], // 默认选中的行
  } = options || {};

  // 选择相关状态
  const selectedRowKeys = ref(
    propsSelectedKeys ?? defaultSelectedRowKeys ?? []
  );
  const selectedRows = ref([]);

  // 更新选中行数据
  const updateSelectedRows = (keys = selectedRowKeys.value) => {
    const rows = [];
    
    if (dataSource.value && Array.isArray(dataSource.value)) {
      keys.forEach(key => {
        const row = dataSource.value.find(item => {
          if (typeof rowKey === 'function') {
            return rowKey(item) === key;
          }
          return item[rowKey] === key;
        });
        
        if (row) {
          rows.push(row);
        }
      });
    }
    
    selectedRows.value = rows;
    
    // 触发选择变化回调
    if (onSelectionChange && typeof onSelectionChange === 'function') {
      onSelectionChange(keys, rows);
    }
  };

  // 处理选择变化
  const handleSelectionChange = (keys, rows) => {
    selectedRowKeys.value = keys;
    selectedRows.value = rows;
    
    // 触发选择变化回调
    if (onSelectionChange && typeof onSelectionChange === 'function') {
      onSelectionChange(keys, rows);
    }
  };

  // 选择全部
  const selectAll = (dataSource) => {
    if (!dataSource || !Array.isArray(dataSource)) return;
    
    const keys = dataSource
      .filter(item => !isSelectable || isSelectable(item))
      .map(item => {
        if (typeof rowKey === 'function') {
          return rowKey(item);
        }
        return item[rowKey];
      });
    
    selectedRowKeys.value = keys;
    updateSelectedRows(keys);
  };

  // 取消全部选择
  const clearSelection = () => {
    selectedRowKeys.value = [];
    selectedRows.value = [];
    
    // 触发选择变化回调
    if (onSelectionChange && typeof onSelectionChange === 'function') {
      onSelectionChange([], []);
    }
  };

  // 行选择配置
  const rowSelection = computed(() => ({
    selectedRowKeys: selectedRowKeys.value,
    onChange: handleSelectionChange,
    getCheckboxProps: (record) => ({
      disabled: isSelectable ? !isSelectable(record) : false,
    }),
    preserveSelectedRowKeys: preserveSelectedOnPageChange,
  }));

  // 如果提供了外部控制的选中行，监听其变化
  if (propsSelectedKeys) {
    watch(propsSelectedKeys, (newKeys) => {
      selectedRowKeys.value = newKeys;
      updateSelectedRows(newKeys);
    });
  }

  // 监听数据源变化，更新选中行
  watch(dataSource, () => {
    if (!preserveSelectedOnPageChange) {
      clearSelection();
    } else {
      updateSelectedRows();
    }
  });

  return {
    // 状态
    selectedRowKeys,
    selectedRows,
    
    // 计算属性
    rowSelection,
    hasSelected: computed(() => selectedRowKeys.value.length > 0),
    selectedCount: computed(() => selectedRowKeys.value.length),
    
    // 方法
    handleSelectionChange,
    selectAll,
    clearSelection,
    updateSelectedRows,
  };
}
